package cn.com.xcf.service.impl;

import cn.com.xcf.dao.mapper.TCheckCostMapper;
import cn.com.xcf.dao.model.TCheckCost;
import cn.com.xcf.dao.model.TCheckCostDetail;
import cn.com.xcf.dao.model.TCheckCostDetailExample;
import cn.com.xcf.dao.model.TCheckCostExample;
import cn.com.xcf.service.CheckCostDetailService;
import cn.com.xcf.service.CheckCostService;
import cn.com.xcf.service.IDGenerator;
import cn.com.xcf.service.base.BaseServiceImpl;
import com.xcf.entity.Page;
import com.xcf.entity.system.User;
import com.xcf.util.PageData;

import org.joda.time.Instant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * TCheckCostService实现
 * @author WongBin
 * @date 2017/11/22.
 */
@Transactional(rollbackFor = Exception.class)
//@Service(value="checkIncomeService")
public class CheckCostServiceImpl extends BaseServiceImpl<TCheckCostMapper, TCheckCost, TCheckCostExample>
        implements CheckCostService {

    @Override
    public void initMapper() {
        super.mapper = this.mapper;
    }
    private TCheckCostMapper mapper;
    public void setMapper(TCheckCostMapper tCheckCostMapper) {
        this.mapper = tCheckCostMapper;
    }

    @Autowired
    CheckCostDetailService detailService;

    @Override
    public List getCheckUndoList(Object param, Map addition, Page page) {
        //PageData pd = new PageData();
        page.getPd().putAll(addition);
        return mapper.queryUndolistPage(page);
    }

    @Override
    public List getCheckList(TCheckCost item,Map addition, Page page) {
        TCheckCostExample qry = new TCheckCostExample();
        qry.createCriteria();
        qry.setPage(page);
        return super.selectByPage(qry,addition,page);
    }

    @Override
    @Transactional
    public void addToCheckList(Object checkId, List undoList, Object operator,String currStatus) throws Exception {
        assert undoList!=null && undoList.size()>0;
        assert !ObjectUtils.isEmpty(checkId);

        final TCheckCost check = mapper.selectByPrimaryKey(Long.valueOf(""+checkId));
        assert check!=null;

        undoList.forEach(item->{
            //添加对账明细数据
            TCheckCostDetail rec = new TCheckCostDetail();
            rec.setCheckId(Long.valueOf(checkId+""));
            //rec.setCreateBy(operator+"");
            //rec.setCreateTime(new java.util.Date());
            //id处理
            rec.setItemId(Long.valueOf(item+""));
            rec.setStatus(CheckCostStatus.APPEND.getFlag()+"");
            rec.setUpdateBy(operator+"");
            rec.setUpdateTime(new java.util.Date());
            detailService.insertSelective(rec);
            //修改对明细的状态为已对账

            //对账金额累加
            //check.setCheckAmount(check.getCheckAmount().add(item.));
            //check.setUpdateBy(operator+"");
            //check.setUpdateTime(rec.getCreateTime());
            //updateByPrimaryKeySelective(check);
        });
        if(currStatus==null){
            currStatus = CheckCostDetailStatus.PRE_CONFIRM.getFlag();
        }
        //费用明细状态锁定
        resetItemStatus(check.getId(),undoList,CheckCostDetailStatus.CREATE.getFlag(),currStatus);
    }

    @Override
    @Transactional
    public void genCheckRecord(List undoList, Object operator,Map param) throws Exception {
        assert undoList!=null && undoList.size()>0;
        assert !ObjectUtils.isEmpty(operator);
        //final TCheckCost check = this.selectByPrimaryKey(Integer.valueOf(""+checkId));
        //assert check!=null;
        User user = (User)operator;
        TCheckCost check = new TCheckCost();
        java.util.Date now = new java.util.Date();
        String payTime=param.get("requirePayTime").toString();
        java.util.Date requestPayTime=null;
        if(payTime!=""&& payTime!=null)
        {  
	        java.time.Instant instant = java.time.Instant.parse(payTime+"T00:00:00Z");
	        requestPayTime=java.util.Date.from(instant);
        }
        check.setUpdateBy(user.getUSER_ID());
        check.setCheckerName(user.getUSERNAME());
        check.setUpdateTime(now);
        check.setCreateDate(now);
        check.setCheckDate(now);
        check.setCheckDept(user.getSKIN());
        check.setCheckDeptName(user.getSKIN());//对帐号生成
        check.setRequestPayTime(requestPayTime);
        PageData pd = new PageData();
        pd.put("checkCode", null);
        check.setCheckCode(this.getCheckCode(pd));
        check.setCheckerId(user.getUSER_ID());
        check.setCheckerName(user.getUSERNAME());
        check.setStatus(CheckCostStatus.CREATE.getFlag()+"");
        check.setCheckAmount(new BigDecimal(""+param.getOrDefault("total","0")));
        mapper.insertSelective(check);
        undoList.forEach(item->{
            //添加对账明细数据
            TCheckCostDetail rec = new TCheckCostDetail();
            rec.setCheckId(check.getId());
            rec.setCreateBy(user.getUSER_ID()+"");
            rec.setCheckerName(user.getUSERNAME());
            rec.setCreateTime(now);
            //TODO id处理
            rec.setItemId(Long.valueOf(item+""));
            rec.setStatus(CheckCostDetailStatus.CREATE.getFlag());
            rec.setUpdateBy(user.getUSER_ID()+"");
            rec.setUpdateTime(rec.getCreateTime());
            detailService.insertSelective(rec);
            //修改费用明细的状态为已对账

            //对账金额累加
            //check.setCheckAmount(check.getCheckAmount().add(item));
        });
        //费用明细状态锁定
        resetItemStatus(check.getId(),undoList,CheckCostDetailStatus.CREATE.getFlag()
                ,CheckCostDetailStatus.PRE_CONFIRM.getFlag());
    }
    
    @SuppressWarnings("unchecked")
	private String getCheckCode(PageData pd)
    {
    	mapper.getCheckCode(pd);
    	return ((Map<String,String>)pd.get("pd")).get("checkCode");
    }

    @Override
    @Transactional
    public void cancelRecord(Object checkId, Object operator) throws Exception {
        TCheckCost rec = mapper.selectByPrimaryKey(Long.valueOf(""+checkId));
        assert rec!=null;
        //费用明细状态回退
        resetItemStatus(checkId,null,CheckCostDetailStatus.PRE_CONFIRM.getFlag()
                ,CheckCostDetailStatus.CREATE.getFlag());

        TCheckCostExample ex = new TCheckCostExample();
        ex.createCriteria().andCheckIdEqualTo(rec.getCheckCode());
        mapper.deleteByExample(ex);

        //核对明细回退
        TCheckCostDetail sel = new TCheckCostDetail();
        sel.setCheckId(rec.getId());
        /*sel.setStatus(CheckCostDetailStatus.CANCEL.getFlag()+"");
        sel.setUpdateBy(operator+"");
        sel.setUpdateTime(new Date());*/
        TCheckCostDetailExample selExample = new TCheckCostDetailExample();
        selExample.createCriteria().andCheckIdEqualTo(sel.getCheckId());
        //detailService.updateByExampleSelective(sel,selExample);
        detailService.deleteByExample(selExample);

    }
    
    @Override
    @Transactional
    public void updatePayRecordFlag(Object checkId, String id,String name) throws Exception {
       
    	
        Map param = new HashMap();
        param.put("checkId", checkId);
        param.put("id", id);
        param.put("name", name);
    	mapper.updatePayFlag(param);
    }

    @Override
    @Transactional
    public void invalidCheckRecordDetails(Object checkId, List detailIds, Object operator) throws Exception {
        TCheckCost rec = mapper.selectByPrimaryKey(Long.valueOf(checkId+""));
        assert rec!=null;
        assert detailIds!=null && detailIds.size()>0;
        detailIds.forEach(item->{
            //核对明细回退
            /*TCheckCostDetail sel = new TCheckCostDetail();
            sel.setItemId(Long.valueOf(item+""));
            sel.setStatus(CheckCostDetailStatus.CANCEL.getFlag()+"");
            sel.setUpdateBy(operator+"");
            sel.setUpdateTime(new Date());*/
            TCheckCostDetailExample selExample = new TCheckCostDetailExample();
            selExample.createCriteria().andItemIdEqualTo(Long.valueOf(""+item));
            //detailService.updateByExampleSelective(sel,selExample);
            detailService.deleteByExample(selExample);
            //核对金额回退
            //rec.setCheckAmount(rec.getCheckAmount().subtract());

        });
        //收款明细解锁
        resetItemStatus(checkId,detailIds,CheckCostDetailStatus.PRE_CONFIRM.getFlag(),
                CheckCostDetailStatus.CREATE.getFlag());
    }

    @Override
    public boolean resetItemStatus(Object checkId, List detailIs, String status, String currStatus) {
        Map param = new HashMap(1);
        if(checkId!=null && detailIs!=null){
            param.put("updateFlag",1);//按单个费用明细修改
            param.put("ids",detailIs);
            param.put("status",status);
            param.put("currStatus",currStatus);
            mapper.updateItemStatus(param);
            return true;
        }
        if(checkId!=null && detailIs==null){
            param.put("updateFlag",2);//按对账单号修改
            param.put("checkId",checkId);
            param.put("status",status);
            param.put("currStatus",currStatus);
            mapper.updateItemStatus(param);
            return true;
        }
        return false;
    }

    @Override
    public List listItemsByCheckId(Object checkId) {
        Map page = new HashMap();
        page.put("checkId",checkId);
        List data = mapper.queryDetailById(page);
        return data;
    }

    @Override
    public List exportUndoList(Map params) {
        return null;
    }

    @Override
    public List exportCheckList(Map params) {
        return null;
    }

    //成本款单单导出
	@Override
	public List<Map> serCostBill(String Exportcostbill) {
		
		return mapper.serCostBill(Exportcostbill);
	}
	//查询部门

	@Override
	public PageData findInfo(PageData pd) {
		
		return mapper.findInfo(pd);
	}

	//发票号为空
	@Override
	public List<Map> serCost(String Exportcostbill) {
		
		return mapper.serCost(Exportcostbill);
	}

	
}